Repository navigation
terminal: attach the window to the kernel shell session by default - #147
Conversation
The windowed terminal spawned a private userspace shell over two pipes
(`--shell-child`), so the window could only ever offer help/ls/cd/pwd/echo/cat/
uname/clear/exit. Everything the user actually wants — df/ps/ppkg/lxrun/id/
groups/su/login/disk/nano, history, line editing, scrollback — lives in the
kernel shell, and a pixel copy of a kernel session can be rendered without
rewriting that shell or inventing a PTY.
`--socket PATH` without `--vt`/`--mirror-vt`/`--demo-shell`/`--pipe-shell` now
opens /dev/vtfb1 (ioctl 0x4700 -> {width,height,stride,bpp=32,generation},
mmap PROT_READ/MAP_SHARED of stride*height) and /dev/vtinput1. Each iteration
polls the generation header; only when it grows does the client blit the whole
frame into the window canvas and forward damage over PDP/1 (ShmSurface when the
compositor offers it). Keys go through keys::encode_key and are written to
/dev/vtinput1 verbatim; the client renders and forwards input, it never fakes a
command. `exit` in the session makes the device return ENODEV: the window shows
"the shell session has ended / relaunch to reconnect", holds it briefly and
closes. Reconnect is a relaunch by choice: the kernel spawns a session on the
first open, and an in-window reconnect prompt would need a keyboard UI the
pixel mirror does not have.
Blit policy (documented in fit_placement): window >= surface -> exact 1:1,
centred, no resampling; window smaller -> aspect-preserving nearest-neighbour
downscale, centred, letterboxed with the theme background. Never cropped (losing
part of a session's output is worse than losing a pixel row) and never
upscaled (blurred magnification is worse than a crisp centred frame).
Failure behaviour is explicit, never a silent demo:
* devices missing (ENOENT, kernel without the surface) -> honest stderr line
and the previous pipe shell session as the fallback;
* devices present but ioctl/mmap/read/write failing -> honest message in the
window, exit code 2, no fallback;
* mmap unavailable -> documented read() snapshot fallback (header + pixels).
All device I/O hides behind `kernelsession::{FrameSource, InputSink}` because
the library crate forbids unsafe; only the thin ioctl/mmap glue lives in the
binary (src/bin/pagh-terminal/devfs.rs). That is what makes this testable: host
CI has no /dev/vtfb1. `tests/kernel_session.rs` drives generation, blit
(1:1/downscale/letterbox), frame-1-only redraws, invalidate-for-full-repaint,
short frames, ENODEV/IO errors, key encoding, FileInput, read() fallback on a
real file, the notice renderer, --help, the missing-device fallback and the
honest error for a broken surface.
Existing demo/pipe paths are unchanged but now explicit (`--demo-shell`,
`--pipe-shell`); the three e2e tests that drive them pass the flag instead of
relying on the old default. Kernel side is not touched: this is the client half
of a contract implemented in parallel; live integration is still pending, so
nothing here claims QEMU verification.
TERMINAL.md promised a text shared surface and a private pipe shell; both are now secondary to the kernel shell-session window. Without this update the docs still say `--socket` starts a userspace shell, which is exactly the behaviour this branch removed from the default. New section "Режим kernel-session (по умолчанию)" records the device contract (ioctl 0x4700 / 24-byte header / mmap / read() fallback / ENODEV), the frame loop (generation gate, full blit, damage 16 ms throttle, 6 ms idle), the blit policy and why it never crops or upscales, key encoding and why arrow keys stay in normal mode, the exit/error matrix (ENODEV notice, missing device -> pipe fallback, broken device -> in-window error, exit code 2), the trait split that makes the mode host-testable, and the gaps that are still open: no PTY/termios/TIOCGWINSZ/SIGWINCH, no terminal job control, no DEC modes on a pixel surface, one session per window, scrollback/selection left in the kernel, and no live QEMU run yet. The pipe-shell section is relabelled as the fallback/test mode it now is, the mode list and module table include kernelsession.rs and devfs.rs, and the checks section carries the real numbers (159 host tests) plus the fact that pdp/shm e2e now pass --demo-shell explicitly instead of relying on the old default.
4b299e8 to
8fd9fa1
Compare
Updating the branch from dev failed only in one place: the import block of
rust-apps/pagh-terminal/src/bin/pagh-terminal.rs. Both sides grew new imports at
the same spot — this branch needs `client::ShmFrame` and the `kernelsession`
items for the default kernel-session window, dev needs `cell::{CELL_WIDE,
CELL_WIDE_CONT}`, `font::{CELL_H, CELL_W}`, `render_screen_into_cleared`,
`screen::CursorStyle`, `{Attrs, Cell, Screen}`, `Damage` and `Rect` for its
cell-run widget damage. The resolution keeps both sets; nothing was dropped.
Everything else merged cleanly and both features are intact:
* kernel-session attach (this branch): `--vt-fb`/`--vt-input`,
`--pipe-shell`/`--demo-shell`, `run_kernel_session` + `devfs` (ioctl 0x4700
/ mmap / read fallback), generation-gated blit into the window;
* dev #161/#164/#155/#158: cell-run damage renderer in the text modes, the
opt-level/row-store changes, pagh-ui damage/layer updates, double-click and
lxrun changes — the text paths keep dev's new damage rendering, the pixel
blurbs of the kernel session are unaffected.
Gates after the merge: `cargo fmt -p pagh-terminal -- --check` (and
`-p pagh-ui`), `cargo test` in the terminal crate (169 tests) and in pagh-ui
(140), static musl build via tools/build-rust-app.sh (static-pie, no INTERP).
`cargo fmt --all --check` in either crate also walks the path-dependency
pagh-desktop, whose src/server.rs is byte-identical to origin/dev and not
rustfmt-clean under this toolchain; that drift is dev's, is outside this PR's
write scope and is left untouched.
2a6bff9 to
129fbad
Compare
|
Sync with dev (1e8b077) — конфликт разрешён
Автоматически слились без конфликтов и сохранены обе стороны: Гейты после merge:
Замечание (не моё и вне scope PR): Live-QEMU по-прежнему не прогонялся: kernel-ветка |
Attaching to a kernel session is invisible on the wire: the client blits pixels
and forwards bytes, so a live run has nothing to grep unless the client says what
it did. Two lines close that gap, and the guest console forwards a process's
stderr to the serial log, which is where live evidence is read from.
On open, the surface path now prints how the pixels were obtained:
pagh-terminal: kernel surface /dev/vtfb1: mmap 3145728 bytes
PROT_READ|MAP_SHARED (ioctl 0x4700 1024x768 stride 4096 bpp 32)
That distinguishes the mmap path (contract primary) from the read() fallback,
whose existing "mmap of … unavailable (…); falling back to read() snapshots"
line stays the counterpart. Without it a green window only proved that *some*
source worked, not which one.
`--vt-trace` logs every drawn frame with its kernel generation:
pagh-terminal: kernel frame generation 42 drawn
Off by default (a full-screen editor repaints a lot, and serial is 115200 baud),
enabled per run for integration evidence: the generation numbers, in order, are
the proof that the frame gate follows the kernel's flushes rather than a frozen
or redundant repaint. The equivalent env var PAGH_TERMINAL_KERNEL_TRACE still
works for hosts that can set it.
No behaviour change: the drawing path, gate and error handling are untouched;
the help/TERMINAL.md document both diagnostics, and the help test asserts the
flag is listed.
…derr
Live integration found the wall the desktop puts in front of its own children.
The compositor starts applications with --launch-target in a BACKGROUND console
process group, and this kernel enables TOSTOP by default, so the app's first
write to stderr raises SIGTTOU and the job is stopped before it can map its
surface (serial: "stopped by pgid 7 (foreground 1) -> SIGTTOU + EINTR"). A
client launched the way the shipped desktop launches it therefore cannot report
anything on stderr — including the kernel-session attach lines.
`--log-file PATH` moves every diagnostic of the mode (surface mapping, ioctl
geometry, connection, per-frame generation with --vt-trace, session end, device
failure) into a file opened in append mode, so a relaunch adds to the previous
run instead of erasing its evidence. Without the flag the sink is stderr exactly
as before, so shell-launched runs and the existing tests are unchanged.
The surface helper no longer prints: devfs returns a note ("kernel surface …
mmap … PROT_READ|MAP_SHARED (ioctl 0x4700 …)") and the binary decides where it
goes, because the sink is client policy and the device layer must stay a thin
unsafe shim.
Also records the second live finding in TERMINAL.md, since both are properties
of the ABI rather than of this client: window input only reaches the session
when the console has no foreground compat process (vtinput::write_session hands
bytes to FG_PID's stdin otherwise), so the terminal must be started by the
compositor — not typed as a shell job; and such a background child must log to a
file because of TOSTOP.
Tests: --log-file case (missing devices + fake compositor: the fallback line
lands in the file, not on stderr), help lists the flag; 170 host tests green.
The desktop launches its applications as background console jobs, so a write to stderr stops them with SIGTTOU. The `--log-file` sink covered the kernel-session runtime, but not the failures that happen before it exists: an unknown argument (which is what a target with an extra `--connect` produces) exited through `eprintln!` and vanished into the TOSTOP stop — the window silently never appears and nothing anywhere says why. `report_fatal` now rescans the raw argv for `--log-file` and appends the fatal line there, falling back to stderr when the flag is absent or the file cannot be opened. Argv is used deliberately: the error may be a parse error, so the normal Args value may not exist yet. Test: `--no-such-flag --log-file F` exits 2 with the error inside F and nothing on stderr (17 kernel-session tests, 171 host tests green).
The guest's Linux layer accepts O_APPEND and ignores it, so every client that opened the diagnostics file wrote from offset 0. Two sequential launches of the terminal — exactly what the relaunch/respawn step does — therefore overwrote each other: the second client's lines landed on top of the first's, including the "kernel surface … mmap" line and the ENODEV end line. A live run read as one corrupted client instead of two. `Diag` and `report_fatal` now open the file and seek to End(0) explicitly, so appending does not depend on a flag this kernel does not honour. Test: two fatal runs against one file keep both "unknown argument" lines. 18 kernel-session tests, 172 host tests green.
Live acceptance on #148 (KVM, release kernel) — evidence in
|
`exit` in the kernel shell makes /dev/vtfb1 answer ENODEV, and the client used
to answer that by closing the window and telling the user to relaunch. Relaunch
is what produced the `duplicate window` blocker: the compositor still held the
window id of the previous client when the new client asked for it, so a reopen
could be refused even though the desktop looked empty.
The window now outlives the session. On ENODEV the client draws the honest notice
("the shell session has ended — press Enter to start a new session in this
window") and stays connected; the next key reopens /dev/vtinput1 and /dev/vtfb1.
The kernel spawns a fresh session on the first open of either device, so the same
window continues on a brand-new session — one `create`, one window id, no second
client for the compositor to arbitrate.
Plumbing: `FrameSource::respawn` / `InputSink::respawn` (defaults are no-ops or
Ended, so mocks and non-device sinks keep working), implemented by
`ReadFrameSource` (fresh open), `MmapSurface` (new open + mmap, old mapping
unmapped, old fd closed) and `FileInput` (fresh open). `KernelFrame::respawn`
resets the generation gate and forces a full blit; a failure is reported honestly
and only then closes the window.
Tests: a finished session restarts in the same canvas (fresh generation, Drawn
again), the input device is reopened for the new session, and the ENODEV message
names Enter instead of "relaunch". 174 host tests green.
The in-window respawn opened the new devices first and only then dropped the old fds. The kernel resets its open-fd counter when a session exits (its fds outlive the session on purpose, frames stay pinned), so the late `close` of the OLD fd after `note_open` of the NEW session drove the counter back to zero, the kernel asked the freshly spawned session to exit, and the surface's ioctl answered ENODEV — the window restarted and died in the same breath. Respawn now closes both old handles first (`FileInput` and `MmapSurface` hold `Option<File>`), and only then opens the input device and the surface. With the counter already at zero the stale `close` is a no-op, and the new session stays alive. Test suite unchanged and green (174); the live evidence for the Enter-respawn path is rerun after this commit.
Closing the old surface fd after the input device had already been reopened still drove the kernel's per-session open counter to zero: the counter is reset when the session exits, so one late `close` is enough to make the kernel ask the just-spawned session to exit, and the next ioctl answers ENODEV. The window restarted and died immediately. Respawn is now two phases over both devices: `close` on the input sink and on the frame source, then `respawn` on the input and on the surface. `FileInput` and `MmapSurface` hold `Option<File>`, so a closed handle is explicit and its late `close` cannot land after the spawn. The pure predicate lives in the trait's docs rather than in a comment beside one call site. Tests cover the hooks (close is called once, reopen follows, sinks keep the close-then-open order); 174 host tests green.
The Enter-respawn path had no visibility into which failed: the client logged only the final ENODEV. It now names the step (devices closed / input reopened / surface pending) and retries the surface ioctl while the error is ENODEV, which is the state a just-spawned session can be in for a moment.
Respawn/reopen: клиентская часть сделана; оставшийся блокер — kernel-путь(a) duplicate-window при respawn — закрыто в клиенте
Коммиты: (b) live: где именно останавливается respawn
— ввод после Скриншоты попытки: Гейты / CI
Kernel-правок в PR нет: input-маршрутизация — #169, respawn-путь поверхности — |
Lead decision: the client keeps a single restart path, the one #167 extends. The parallel `awaiting_respawn`/`notice_pending` flags are gone; ENODEV now goes through `wait_for_restart` with #167's name, signature, notice text and key semantics: Enter/Space restarts the session in this window, Esc (or a server close) closes it. `draw_notice_frame` is the same helper #167 uses to put the notice on screen, so merging the branches does not change behaviour. `respawn_kernel_session` stays as the #147-specific mechanics behind that door: close both old devices, then reopen input and surface, so the kernel's open-counter cannot drop to zero between the two opens (that is what made the first restart attempt answer ENODEV). The log line the live acceptance greps ("kernel session restarted in the same window (generation N)") is unchanged. 174 host tests green; docs describe Enter/Space vs Esc.
`KernelFrame` holds `Box<dyn FrameSource>`; the blanket impl forwarded only `poll` and `with_pixels`, so `close`/`respawn` were served by the trait's DEFAULT bodies (`Ok(())` / `Err(Ended)`). The real device was never touched: the Enter-restart logged "devices closed → input reopened" (that part is a concrete `KeyForwarder<FileInput>`) and then failed instantly with the generic Ended message, which looked exactly like a kernel refusal but came from the client. The blanket impl now forwards both methods, and a test pins it: a boxed mock source must close and respawn for real (fresh generation, Drawn again). Without this, every restart attempt after `exit` was a no-op dressed as ENODEV. 175 host tests green.
Финальный live Enter-respawn на dev+#174 — PASS (15/16, единственный FAIL — устаревшая проверка драйвера)Ветка ребейзена на
Diff (по решению lead)
Гейты / CI
|
…indow Adds 'tools/e2e.py termwindow', the stage-2 acceptance that #147/#169 made possible: the shipped pagh-desktop + pagh-terminal pair runs on the real fbdev/evdev/PDP path, and the window itself is kernel-shell session 1 (/dev/vtfb1 pixels + /dev/vtinput1 keys), so every command is the kernel shell's own code, not a userspace imitation. The compositor is started from /mnt/etc/autorun — the shipped desktop-autorun recipe. That is not cosmetic: the launch-target spec contains '{socket}', and typing shifted braces through QMP left a stuck modifier under TCG, so the next 'c' reached the guest as a real ^C. With autorun, the only keys on the wire are the commands under test. Per command the mode records one PNG (what a human sees) and one '[DIAG] window session=1 command=…/done=…' serial pair (the kernel's own evidence that the line reached and returned from session-shell). It fails if any kernel-shell output appears on serial — that would mean the command executed in the boot shell instead — reads the nano buffers back out of the ext2 image with debugfs, and uses the kernel's 'stuck in syscall read' watchdog line to know when the Linux editor is ready for keys. Covered: df, ps, ps -ef, id, id -un, groups, ls -la /mnt, disk list, clear, help, kernel nano (edit/Ctrl+S/Ctrl+Q), ppkg update, ppkg install nano fastfetch ncurses-base, bare fastfetch (PATH fallback without lxrun) and lxrun nano (Ctrl+O/Enter/Ctrl+X). A 256 MiB volume is created because the 64 MiB desktop image cannot hold ppkg install. Known gap, reported rather than papered over: the Linux (ncurses) nano opens and renders, and an earlier run saved its file (read back from ext2), but in later runs the editor parked in read(2) without receiving the Ctrl+O/Enter/Ctrl+X chords — termios/raw-mode, i.e. the named stage-3 PTY/job-control work, not window routing. Docs: tools/README.md bullet + terminal-session.md §7.
The kernel now keeps winsize/SIGWINCH per console session, but the window client never told it the window changed size: a TUI inside the session could not react to a compositor resize. On every Configure (and once at startup) the client converts its client area to the kernel cell grid (8x18 px, integer division, one-cell floor, u16 clamp) and issues TIOCSWINSZ on /dev/vtinput1. The kernel stores the session's size and queues SIGWINCH to its foreground group; an unchanged size is a no-op on both sides. The ioctl stays in the devfs unsafe module; the cell arithmetic is a pure host-tested function (tests/kernel_session.rs). The client documents the resize contract and the honest boundary: winsize is the app-facing cell size, the pixel surface is still screen-sized and scaled by the client. Stacked on origin/feat/terminal-kernel-client (PR #147) so the live window can be driven end to end before #147 merges; rebase once it lands in dev.
Sync with dev=c1e80933 (#147/#175/#176/#178: console grid from real framebuffer, scrollback/selection, rubberband fullscreen, os-identity, docs). Conflict: src/test.rs only — both sides appended routines/modules at the same two places. Resolution keeps BOTH: - dev qbug2 "console::text grid matches the framebuffer resolution" (console_grid_tests) and the USB "usb::BOT/SCSI/uevent layouts and /usb root rule" (usb_storage_prop_tests); - both modules are present and closed; all_tests registers 126 routines. All USB S1 files are untouched by these dev changes, and the dev framebuffer/console/scrollback/selection/os-identity work is preserved verbatim. AGENTS.md auto-merged and keeps the USB S1 gap text. Post-merge evidence: gates 6/6 (host 885/0), QEMU usb-storage acceptance 46/46, release-kernel selftest 126 routines / 0 failed / 1 skipped (NVMe absent), in one flocked run.
test(live): stage 2 — full kernel shell in a real desktop window (stacked on #147)
Что это
Оконный режим терминала по умолчанию — attach к настоящей kernel-shell-сессии
ядра. Раньше окно спавнило приватный userspace-shell (
--shell-child:help/ls/cd/pwd/echo/cat/uname/clear/exit) и потому не могло показать ни
df,ни
ps, ниppkg/lxrun/disk/nano, ни history/редактирование строки.Теперь
pagh-terminal --socket PATH(без--vt/--mirror-vt/--pipe-shell/--demo-shell) открывает/dev/vtfb1(ioctl0x4700→ 24 байта LE{width,height,stride,bpp=32,generation},mmap(PROT_READ,MAP_SHARED)) и/dev/vtinput1, блитит изменившийся поgenerationкадр в окно и передаётклавиши как VT-байты (
keys::encode_key). Клиент рендерит и передаёт ввод —команды, эхо, редактирование и scrollback делает ядро. Ничего не имитируется.
Контракт (не менялся)
/dev/vtfb10x4700,generationрастёт на flush,ENODEVпослеexit,read()fallback = заголовок + пиксели/dev/vtinput1/dev/vtinput)Поведение
generationвыросла; полный блит (частичных damage v1 не даёт; «порванный» flush'ем кадр
лечится следующим полным). Отправка 16 мс, холостой виток 6 мс.
invalidate()на resize/новый memfd. ShmSurface — если композитор объявил bit 2, иначе
полный кадр.
пропорциональный nearest-neighbour downscale по центру с полями фона. Обрезки
нет (спрятать вывод хуже, чем потерять строку пикселей), апскейла нет (мыло
хуже чёткого центрированного кадра).
KeyModes::default()(пиксельная поверхность не несёт DEC-режимов), release/модификаторы → пусто,
Ctrl+C— байт0x03, сигналыдоставляет ядро.
exitв сессии (ENODEV): в окне «the shell session has ended / relaunchto reconnect», пауза 1.5 с, окно закрывается. Реконнект = перезапуск окна
(сессию спавнит ядро на первом
open); отдельный prompt-UI в пиксельномзеркале в этом этапе не делался — это осознанный выбор, описан в TERMINAL.md.
ENOENT) → честная строка в stderr + откат напрежнюю pipe-сессию; устройства есть, но ioctl/mmap/read/write ломаются →
честное сообщение в окне + код 2, без отката в демо; mmap недоступен →
задокументированный
read()fallback; короткий кадр →ShortRead.Как это тестируется без ядра
lib.rs—#![forbid(unsafe_code)], поэтомуmmap/ioctlживут только вsrc/bin/pagh-terminal/devfs.rs, а вся логика — вsrc/kernelsession.rsзатрейтами
FrameSource/InputSink. Host-тесты (tests/kernel_session.rs, 15)гоняют generation-гейт, блит 1:1/downscale/letterbox, invalidate, short frame,
ENODEV/IO, клавиши,FileInput,read()-fallback на обычном файле, рендерсообщения,
--help, откат на pipe-сессию и честную ошибку без композитора.Гейты (локально)
Kernel-гейты не трогались:
src/**этим PR не изменён. Версия не бампалась.Честные остатки
параллельно и в base (
dev) её ещё нет; kernel-веткаfeat/terminal-kernel-sessionне найдена наorigin(git ls-remote:только
dev,main,integration/*,postmerge/desktop-dev), так чтособрать ядро с устройствами было не из чего. Первый live-прогон должен
подтвердить три пункта:
generationрастёт на flush,mmap-пиксели видныклиенту,
ENODEVпослеexitдоходит до окна как «сессия завершена».TIOCGWINSZ/SIGWINCH (размер знает только ядро), terminaljob-control;
Ctrl+Z— байт в/dev/vtinput1.в окно не транслируются.
--demo-shell,--pipe-shell);три e2e-теста, которые их проверяют, передают флаг вместо старого дефолта.
Notes:
~/.cache/pagh-agent-notes/qterm-client.md